package com.IT.servletJsp.medicine;

import com.IT.service.AdminFunctionService;
import com.IT.service.Impl.AdminFunctionServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet(value = "/admin/addMedicine")
public class AddMedicineJsp extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html; charset = utf-8");

        PrintWriter printWriter = response.getWriter();
        String mName = request.getParameter("mName");

        Date dNow = new Date();
        SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String createDate = ft.format(dNow);

        String updateDate = createDate;

        AdminFunctionService adminFunctionService = new AdminFunctionServiceImpl();
        int flag = adminFunctionService.addMedicine(mName, createDate, updateDate);

        if(flag == 1){
            //printWriter.print("增加药品成功！！");
            //response.sendRedirect("/adminInterface.html");
            printWriter.print("<script>alert('新增药品成功！');window.location.href='/adminInterface.html'</script>");
        }
        else if(flag == -1){
            //printWriter.print("新增失败！！");
            printWriter.print("<script>alert('药品已存在！');window.location.href='/addMedicine.html'</script>");
        }else {
            //flag == 0;数据库操作异常
            printWriter.print("<script>alert('数据库操作异常！');window.location.href='/addMedicine.html'</script>");
        }
    }
}
